import { asyncRoutes, constantRoutes } from '@/router'
import { getUserMenu } from '@/Yapi/java/modules/handelLogin.js'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
function generaMenu(routes, data, roles) {
  data.forEach(item => {
    const menu = {
      path: item.path,
      component: item.component === 'Layout' ? Layout : (resolve) => require([`@/views${item.component}`], resolve),
      redirect: item.redirect,
      hidden: !!item.hidden,
      children: [],
      name: item.name,
      meta: { title: item.title, id: item.id, icon: item.icon, noCache: item.hidden, roles: roles, showBack: item.hidden, keepAlive: true }
    }
    if (item.children && item.children.length > 0) {
      generaMenu(menu.children, item.children, roles)
    }
    routes.push(menu)
  })
}

const state = {
  routes: [],
  addRoutes: [],
  preRoutes: null
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  UPDATE_PREROUTES: (state, route) => {
    state.preRoutes = route
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      const loadMenuData = []
      getUserMenu().then(response => {
        const { result } = response
        generaMenu(loadMenuData, result, roles)
        let accessedRoutes = filterAsyncRoutes(loadMenuData, roles)

        accessedRoutes = accessedRoutes.concat(asyncRoutes)

        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch((error) => {
        console.log(error)
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
